<template>
	<div class="table-mechanism">
		<div class="tableHeader">
			<el-input style="width: 200px; margin-right: 20px;" @change="search()" v-model.trim="queryForm.templateName" autocomplete="off" placeholder="请输入套餐名称搜索"></el-input>
			<el-button @click="addPlanVisible = true; planIsEdit = false; searchOfPackageOfConditions()">添加护理计划模板</el-button>
		</div>
		<el-table :data="list" v-loading="listLoading">
			<el-table-column show-overflow-tooltip="" min-width="100" label="模板名称" prop="templateName"></el-table-column>
			<el-table-column show-overflow-tooltip="" min-width="150" label="模板编号" prop="templateNumber"></el-table-column>
			<el-table-column prop="packageName" label="套餐名称" min-width="100"></el-table-column>
			<el-table-column label="创建时间" min-width="180">
				<template slot-scope="scope">
					{{scope.row.createTime | parseTime()}}
				</template>
			</el-table-column>
			<el-table-column label="操作" prop="disabled" min-width="160px" fixed="right">
				<!--  v-permission="'but'" -->
				<template slot-scope="scope">
					<el-button type="text" @click="projectVisible = true; activePlanRow = scope.row; getProjectlist(1)" v-if="!scope.row.disabled">护理项目</el-button>
					<el-button type="text" v-if="!scope.row.disabled" @click="enablePlan(scope.row.templateNumber, scope.row.disabled)">禁用</el-button>
					<el-button type="text" v-else @click="enablePlan(scope.row.templateNumber, scope.row.disabled)">启用</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:background="background"
			:current-page=queryForm.currPageNo
			:total="total"
			:page-size="queryForm.limit"
			@current-change="handleCurrentChange"
			@size-change="handleSizeChange"
		></el-pagination>

		<el-dialog
			title="添加护理计划模板"
			:visible.sync="addPlanVisible"
			width="500px"
		>
			<el-form ref="addPlanform" :model="addPlanform" :rules="planRules" label-width="120px" >
				<el-form-item label="模板名称" prop="templateName">
					<el-input style="width: 200px;" v-model.trim="addPlanform.templateName" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="套餐" prop="packageMark">
					<el-select v-model="addPlanform.packageMark" placeholder="请选择">
						<el-option
							v-for="item in packageOfConditions"
							:key="item.mark"
							:label="item.name"
							:value="item.mark">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addPlanVisible = false" >取 消</el-button>
				<el-button type="primary" @click="savePlan">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog
			title="护理项目"
			:visible.sync="projectVisible"
			width="800px"
		>
			<div class="header">
				<el-button @click="searchProjectInside()">添加套餐护理项目</el-button>
				<el-button @click="openProject()">添加套餐外护理项目</el-button>
			</div>
			<br>
			<div class="planlist">
				<el-table
					:data="projectlist"
					v-loading="projectlistLoading"
				>
					<el-table-column
						show-overflow-tooltip
						label="项目名称"
						prop="nursingItemName"
					></el-table-column>
					<el-table-column label="是否收费">
						<template slot-scope="scope">
							{{ scope.row.charge ? '是' : '否'}}
						</template>
					</el-table-column>
					<el-table-column label="执行费用">
						<template slot-scope="scope">
							{{ scope.row.price }}
						</template>
					</el-table-column>
					<el-table-column label="执行周期">
						<template slot-scope="scope">
							{{ scope.row.unit == 2 ? '月' : '天'}}
						</template>
					</el-table-column>
					<el-table-column
						show-overflow-tooltip
						label="执行周期间隔"
						width="120"
						prop="cycle"
					></el-table-column>
					</el-table-column>
					<el-table-column label="操作" prop="disabled"  width="140px"  fixed="right">
						<template slot-scope="scope">
							<!-- <el-button type="text" @click="planVisible = true">套餐项目</el-button>
							<el-button type="text">套餐外项目</el-button>
							<el-button type="danger" @click="enablePlan(id, scope.row.state)">禁用</el-button> -->
							<el-button type="text" @click="editProject({ ...scope.row })">编辑</el-button>
							<el-button type="text" v-if="!scope.row.disabled" @click="enableProject(false, { ...scope.row })">禁用</el-button>
							<el-button type="text" v-else @click="enableProject(true, { ...scope.row })">启用</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- <el-pagination
					:background="background"
					:current-page=projectQueryForm.currPageNo
					:total="projectTotal"
					:page-size="projectQueryForm.limit"
					@current-change="projectHandleCurrentChange"
					@size-change="projectHandleSizeChange"
				></el-pagination> -->
			</div>
		</el-dialog>

		<el-dialog
			:title="isEditProject ? '编辑套餐护理项目' : '添加套餐护理项目'"
			:visible.sync="addProjectVisibleInside"
			width="560px"
		>
			<el-form ref="addProjectFormInside" :model="addProjectFormInside" :rules="addProjectRulesInside" label-width="140px" >
				<el-form-item label="项目" prop="itemMark">
					<el-select
						:disabled="isEditProject"
						v-model="addProjectFormInside.itemMark"
						filterable
						reserve-keyword
						placeholder="请输入项目关键词">
						<el-option
							v-for="item in searchProjectOptionsInside"
							:key="item.itemMark"
							:label="item.itemName"
							:value="item.itemMark">
							<div class="itemBox">
								<span>名称：{{ item.itemName }}</span>
								<span>日护理次数：{{ item.dailyNumberOfCare }}</span>
								<span>月护理次数：{{ item.monthNumberOfCare }}</span>
								<span>总护理次数：{{ item.totalNumberOfCare }}</span>
							</div>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="执行周期单位" prop="unit">
					<el-select
						v-model="addProjectFormInside.unit"
						@change="addProjectFormInside.executionTimes = [{}]"
						placeholder="请选择周期单位">
						<el-option label="月" :value="2"></el-option>
						<el-option label="天" :value="3"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="执行周期间隔数" prop="cycle">
					<el-input-number v-model="addProjectFormInside.cycle" :min="0" :max="999"></el-input-number>
				</el-form-item>
				<el-form-item label="周期内执行时间" prop="executionTimes">
					<div v-for="(item, index) in addProjectFormInside.executionTimes" class="timeBox">
						<template v-if="addProjectFormInside.unit == 2">
							<el-input-number controls-position="right" style="width:84px" v-model="item.d" :min="0" :max="31"></el-input-number> 天
						</template>
						<el-input-number controls-position="right" style="width:84px" v-model="item.h" :min="0" :max="24"></el-input-number> 时
						<el-input-number controls-position="right" style="width:84px" v-model="item.m" :min="0" :max="60"></el-input-number> 分
						<!-- <el-time-picker v-model="item.value" value-format="timestamp"></el-time-picker> -->
						<i class="el-icon-minus" v-if="index" @click="delTimeItem(index)"></i>
						<i class="el-icon-plus" v-else @click="addProjectFormInside.executionTimes.push({})"></i>
					</div>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addProjectVisibleInside = false" >取 消</el-button>
				<el-button type="primary" @click="addProjectInside">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog
			:title="isEditProject ? '编辑套餐外护理项目' : '添加套餐外护理项目'"
			:visible.sync="addProjectVisible"
			width="560px"
		>
			<el-form ref="addProjectForm" :model="addProjectForm" :rules="addProjectRules" label-width="140px" >
				<el-form-item label="项目" prop="itemMark">
					<search-input :disabled="isEditProject" v-model="addProjectForm.itemMark" :config="sConfig" :searchName="searchName" @change="projectMarkChange2" placeholder="请输入项目关键词"></search-input>
					<!-- <el-select
						v-model="addProjectForm.itemMark"
						filterable
						remote
						@change="projectMarkChange"
						reserve-keyword
						placeholder="请输入项目关键词"
						:remote-method="searchProject"
						:loading="searchProjectLoading">
						<el-option
							v-for="item in searchProjectOptions"
							:key="item.mark"
							:label="item.name"
							:value="item.mark">
							<div class="itemBox">
								<span style="float: left">{{ item.name }}</span>
								<span v-if="item.fee" style="float: right; color: #8492a6; font-size: 13px">价格：{{ item.fee }}</span>
							</div>
						</el-option>
					</el-select> -->
				</el-form-item>
				<div v-show="addProjectForm.itemMark">
					<el-form-item label="是否收费" prop="charged">
						{{ activeProjectlRow.charged ? '是' : '否' }}
					</el-form-item>
					<el-form-item v-show="activeProjectlRow.charged" label="执行费用" prop="price">
						<el-input-number v-model="addProjectForm.price" :min="0" :disabled="!activeProjectlRow.charge"></el-input-number>
					</el-form-item>
				</div>
				<el-form-item label="执行周期单位" prop="unit">
					<el-select
						v-model="addProjectForm.unit"
						@change="addProjectForm.executionTimes = [{}]"
						placeholder="请选择周期单位">
						<el-option label="月" :value="2"></el-option>
						<el-option label="天" :value="3"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="执行周期间隔数" prop="cycle">
					<el-input-number v-model="addProjectForm.cycle" :min="0" :max="999"></el-input-number>
				</el-form-item>
				<el-form-item label="周期内执行时间" prop="executionTimes">
					<div v-for="(item, index) in addProjectForm.executionTimes" class="timeBox">
						<template v-if="addProjectForm.unit == 2">
							<el-input-number controls-position="right" style="width:84px" v-model="item.d" :min="0" :max="31"></el-input-number> 天
						</template>
						<el-input-number controls-position="right" style="width:84px" v-model="item.h" :min="0" :max="24"></el-input-number> 时
						<el-input-number controls-position="right" style="width:84px" v-model="item.m" :min="0" :max="60"></el-input-number> 分
						<!-- <el-time-picker v-model="item.value" value-format="timestamp"></el-time-picker> -->
						<i class="el-icon-minus" v-if="index" @click="delTimeItem1(index)"></i>
						<i class="el-icon-plus" v-else @click="addProjectForm.executionTimes.push({})"></i>
					</div>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="addProjectVisible = false" >取 消</el-button>
				<el-button type="primary" @click="addProject">确 定</el-button>
			</div>
		</el-dialog>

	</div>
</template>

<script>
	import { searchCarePlanTemplateOfConditions, searchOfPackageOfConditions, addTemplate, enableCarePlanTemplate, disableOrEnableNursePlanItem, addMealItemPlanToTemplate, addExtraItemPlanToTemplate, modifyExtraItemPlanToTemplate, modifyMealItemPlanToTemplate, searchCarePlanTemplateContentVO, disableCarePlanTemplateContent, enableCarePlanTemplateContent, searchmeal, searchAllItemInfos } from "@/api/template"
	import { parseTime} from "@/utils/index";
	import searchInput from '@/components/searchInput'
	export default {
		name: "Template",
		components: {
			searchInput
		},
		filters:{
			parseTime: parseTime
		},
		data() {
			return {
				sConfig: {
					api: '/sinohis/pension/fee/itemmanager/searchAllItemInfos',
					method: 'post',
					postKey: 'mnemonicCodeOrName',
					label: 'name',
					value: 'mark',
					data: { nurseItemBol: true },
					keys: [
						{ name: '名称', key: 'name' },
						{ name: '价格', key: 'fee' },
					]
				},
				searchName: '',
				checkedInTime: [],
				listLoading: true,
				total: 0,
				planTotal: 0,
				background: true,
				id: 0,
				list: [],
				planVisible: false,
				planIsEdit: false,
				addPlanVisible: false,
				planlist: [],
				planlistLoading: false,
				addPlanform: {},
				activeRow: {},
				projectVisible: false,
				activePlanRow: {},
				addProjectVisible: false,
				queryForm: {
					currPageNo: 1,
					limit: 10,
					elderlyCode: '',
				},
				planQueryForm: {
					currPageNo: 1,
					limit: 10,
				},
				projectQueryForm: {
					// currPageNo: 1,
					// limit: 10,
				},
				projectlist: [],
				projectlistLoading: false,
				projectTotal: 0,
				addProjectValue: '',

				planRules: {
					templateName: [
		            	{ required: true, message: '请输入模板名称', trigger: 'blur' },
		        	],
					packageMark: [
					    { required: true, message: '请选择套餐', trigger: 'change' }
					],
				},
				searchProjectLoading: false,
				searchProjectOptions: [],
				addProjectForm: {},
				addProjectRules: {
					itemMark: [
					    { required: true, message: '请选择项目', trigger: 'change' }
					],
					unit: [
					    { required: true, message: '请选择执行周期单位', trigger: 'change' }
					],
					cycle: [
					    { required: true, message: '请输入间隔数', trigger: 'change' }
					],
					executionTimes: [
					    { type: 'array', required: true, message: '请选择周期内执行时间', trigger: 'change' }
					],
					startExecTime: [
					    { required: true, message: '请选择开始时间', trigger: 'change' }
					],
				},
				addProjectVisible: false,
				addProjectVisibleInside: false,
				searchProjectOptionsInside: [],
				addProjectFormInside: {
					executionTimes: [{value: ''}]
				},
				addProjectRulesInside: {
					itemMark: [
					    { required: true, message: '请选择项目', trigger: 'change' }
					],
					unit: [
					    { required: true, message: '请选择执行周期单位', trigger: 'change' }
					],
					cycle: [
					    { required: true, message: '请输入间隔数', trigger: 'change' }
					],
					executionTimes: [
					    { type: 'array', required: true, message: '请选择周期内执行时间', trigger: 'change' }
					],
					startExecTime: [
					    { required: true, message: '请选择开始时间', trigger: 'change' }
					],
				},
				activeProjectlRow: {},
				activeProjectlRow1: {},
				isEditProject: false,
				packageOfConditions: [],
			};
		},
		created(){
			this.queryForm.institutionNumber= JSON.parse(localStorage.getItem("institutionNumber"));
			this.search()
		},
		methods: {
			search(){
				this.listLoading = true;
				searchCarePlanTemplateOfConditions(this.queryForm).then(res =>{
                    this.list = res.data.data
                    this.total = res.data.total
                    setTimeout(() => {
                        this.listLoading = false;
                    }, 50);
                })
			},
			searchOfPackageOfConditions(){
				searchOfPackageOfConditions({ currPageNo: 1, limit: 99999 }).then(res => {
					this.packageOfConditions = res.data.data
				})
			},
			handleSizeChange(val) {
				this.queryForm.limit = val;
				this.search();
			},
			handleCurrentChange(val) {
				this.queryForm.currPageNo = val;
				this.search();
			},

			projectHandleSizeChange(val) {
				this.planQueryForm.limit = val;
				this.getProjectlist();
			},
			projectHandleCurrentChange(val) {
				this.planQueryForm.currPageNo = val;
				this.getProjectlist();
			},
			savePlan(){
				this.$refs['addPlanform'].validate(async (valid) => {
                    if (valid) {
                    	this.addPlanform.checkInIdentify = this.activeRow.checkInMark
                    	addTemplate(this.addPlanform).then(res => {
                			this.addPlanVisible = false
                			this.queryForm.currPageNo = 1
                			this.search()
                		})
                    }
                })
			},
			enablePlan(templateNumber, state){
				if(!state){
					disableOrEnableNursePlanItem({templateNumber}).then(res => {
						this.search()
					})
				}else{
					enableCarePlanTemplate({templateNumber}).then(res => {
						this.search()
					})
				}
			},
			getProjectlist(type){
				this.projectlistLoading = true
				this.projectQueryForm.templateNumber = this.activePlanRow.templateNumber
				searchCarePlanTemplateContentVO(this.projectQueryForm).then((res) => {
					this.projectlist = res.data
	                // this.projectTotal = res.data.total
	                setTimeout(() => {
	                    this.projectlistLoading = false;
	                }, 50);
				})
			},
			addProject(){
				this.$refs['addProjectForm'].validate(async (valid) => {
                    if (valid) {
                    	let times = [...this.addProjectForm.executionTimes]
                    	let timeList = []
                    	let timeString = []
                    	for(let i=0; i<times.length; i++){
                    		let item = times[i]
                    		let itemList = []
                    		itemList.push(item.d >= 0 ? item.d : null)
                    		itemList.push(item.h >= 0 ? item.h : null)
                    		itemList.push(item.m >= 0 ? item.m : null)
                    		timeList.push(itemList)
                    		let timeStringItem = (item.d >= 0 ? item.d : 0) + '' + item.h + '' + item.m

                    		if(timeStringItem.length > 6){
                    			this.$baseMessage('执行时间不能为空', 'error')
                    			return false
                    		}
                    		timeString.push(timeStringItem)
                    	}
                    	if(Array.from(new Set(timeString)).length < timeString.length){
                    		this.$baseMessage('执行时间不能重复', 'error')
                    		return false
                    	}
                    	let addForm = {...this.addProjectForm}
                    	addForm.executionTimes = timeList
                    	addForm.templateNumber = this.activePlanRow.templateNumber

                    	if(this.isEditProject){
                    		modifyExtraItemPlanToTemplate(addForm).then(res => {
                    			this.getProjectlist()
                    			this.addProjectVisible = false
                    		})
                    	}else{
                    		addExtraItemPlanToTemplate(addForm).then(res => {
	                    		this.getProjectlist()
	                    		this.addProjectVisible = false
	                    	})
                    	}

                    }
                })
			},
			addProjectInside(){
				// this.isEditProject = false
				this.$refs['addProjectFormInside'].validate(async (valid) => {
                    if (valid) {
                    	let times = [...this.addProjectFormInside.executionTimes]
                    	let timeList = []
                    	let timeString = []
                    	for(let i=0; i<times.length; i++){
                    		let item = times[i]
                    		let itemList = []
                    		itemList.push(item.d >= 0 ? item.d : null)
                    		itemList.push(item.h >= 0 ? item.h : null)
                    		itemList.push(item.m >= 0 ? item.m : null)
                    		timeList.push(itemList)
                    		let timeStringItem = (item.d >= 0 ? item.d : 0) + '' + item.h + '' + item.m

                    		if(timeStringItem.length > 6){
                    			this.$baseMessage('执行时间不能为空', 'error')
                    			return false
                    		}
                    		timeString.push(timeStringItem)
                    	}
                    	if(Array.from(new Set(timeString)).length < timeString.length){
                    		this.$baseMessage('执行时间不能重复', 'error')
                    		return false
                    	}
                    	let addForm = {...this.addProjectFormInside}
                    	addForm.executionTimes = timeList
                    	addForm.templateNumber = this.activePlanRow.templateNumber
                    	// addForm.tcMark = this.activePlanRow.templateNumber
                        console.log(addForm.tcMark)
                    	if(this.isEditProject&&addForm.tcMark!=null){

                    		modifyMealItemPlanToTemplate(addForm).then(res => {
                    			this.getProjectlist()
                    			this.addProjectVisibleInside = false
                    		})
                    	}else{

                    		addMealItemPlanToTemplate(addForm).then(res => {
                    			this.getProjectlist()
                    			this.addProjectVisibleInside = false
                    		})
                    	}
                    }
                })
			},
			searchProjectInside(){
				this.isEditProject = false
				searchmeal({ mark: this.activePlanRow.packageMark }).then(res => {
					this.searchProjectOptionsInside = res.data.packageItems
				})
				this.addProjectVisibleInside = true;
				this.addProjectFormInside = {
					executionTimes: [{}]
				}
				this.$nextTick(() => {
					this.$refs['addProjectFormInside'].clearValidate();
				})
			},
			openProject(){
				this.searchName = ''
				this.addProjectVisible = true
				this.isEditProject = false
				this.addProjectForm = {
					executionTimes: [{value: ''}]
				}
				this.$nextTick(() => {
					this.$refs['addProjectForm'].clearValidate();
				})
			},
			searchProject(mnemonicCodeOrName) {
				// this.addProjectVisible = true
				if (mnemonicCodeOrName !== '') {
					this.searchProjectLoading = true;
					searchAllItemInfos({ mnemonicCodeOrName: mnemonicCodeOrName, nurseItemBol: true }).then(res => {
						this.searchProjectLoading = false;
						this.searchProjectOptions = res.data
					})
				} else {
					this.searchProjectOptions = [];
				}
			},
			delTimeItem(index){
				this.addProjectFormInside.executionTimes.splice(index, 1)
			},
			delTimeItem1(index){
				this.addProjectForm.executionTimes.splice(index, 1)
			},
			projectMarkChange(val){
				this.activeProjectlRow = this.searchProjectOptions.find(item => item.mark === val)
				this.addProjectForm.price = this.activeProjectlRow.fee
				this.addProjectForm.charge = this.activeProjectlRow.charged
			},
			projectMarkChange2(row){
				this.activeProjectlRow = row
				this.searchName = row.name
				this.addProjectForm.price = this.activeProjectlRow.fee
				this.addProjectForm.charge = this.activeProjectlRow.charged
			},
			projectMarkChange1(val){
				this.activeProjectlRow1 = this.searchProjectOptions.find(item => item.mark === val)
				this.addCareListItemForm.execPrice = this.activeProjectlRow1.fee
			},
			editProject(row){
			    console.log(row)
				this.isEditProject = true
				let isInside = row.mealItem

				if(isInside){
					searchmeal({ mark: this.activePlanRow.packageMark }).then(res => {
						this.searchProjectOptionsInside = res.data.packageItems

          })
					this.addProjectVisibleInside = true;
				}else{
					// this.searchProject(row.nursingItemName)
					this.searchName = row.nursingItemName
					this.addProjectVisible = true;
				}

				let a = row.executionTimes || ','
                let c = []
      if(row.executionTimes){
          for (let  i=0;i<row.executionTimes.length;i++){

              let b = {}
              let d = row.executionTimes[i]
              b.d = parseInt(d[0])
              b.h = parseInt(d[1])
              b.m = parseInt(d[2])
              c.push(b)

          }
         console.log(c)
          if(c.length>0){
              row.executionTimes = c
          }else {

              row.executionTimes = [{}]

          }

      }else {
          row.executionTimes = [{}]
      }




				// a = a.substring(0, a.length - 1)
				// a = a.split('&')
				// let c = []
				// a.forEach(item => {
				// 	let b = {}
				// 	let d = item.split('-')
				// 	b.d = parseInt(d[0])
				// 	b.h = parseInt(d[1])
				// 	b.m = parseInt(d[2])
				// 	c.push(b)
				// })
				// row.executionTimes = c
				row.itemMark = row.nursingItemMark

				if(isInside){
					this.addProjectFormInside = row
				}else{
					this.addProjectForm = row
				}
			},
			enableProject(type, row){
				let tcMark = row.tcMark
				if(!type){
					disableCarePlanTemplateContent({tcMark}).then(res => {
						this.getProjectlist()
					})
				}else{
					enableCarePlanTemplateContent({tcMark}).then(res => {
						this.getProjectlist()
					})
				}
			},
		},
	}
</script>

<style scoped>
	.timeBox{margin-bottom: 10px;}
	.timeBox:last-child{margin-bottom: 0;}
	.timeBox i{cursor: pointer;color: #1890ff;margin-left: 10px;}
	.itemBox{}
	.itemBox span{display: inline-block;overflow: hidden; white-space: nowrap; text-overflow: ellipsis;width: 120px;}
	.itemBox span:first-child{width: 130px;}

	.table-mechanism >>> .el-table .warning-row {background: oldlace;opacity: 0.5;}
	.table-mechanism >>> .el-table .success-row {background: #f0f9eb;}
	.tableHeader{padding:20px 10px;}
</style>
